<?php
namespace app\common\library\pay;

use app\common\enum\order\PayType as OrderPayTypeEnum;
use app\common\enum\OrderType as OrderTypeEnum;
use app\common\exception\BaseException;
use app\common\library\helper;
use app\common\service\Pay as ChannelPay;

class Pay{
    // 订单模型
    private $modelClass = [
        OrderTypeEnum::ORDER => 'app\api\service\order\PaySuccess',
        OrderTypeEnum::RECHARGE => 'app\api\service\recharge\PaySuccess',
    ];

    /**
     * 支付成功异步通知
     * @throws BaseException
     * @throws \Exception
     */
    public function notify()
    {
        if (!$jsonStr = file_get_contents('php://input')) {
            $this->returnCode(false, 'Not found DATA');
        }

        // 记录日志
        log_record($jsonStr);
        // 将服务器返回的XML数据转化为数组
        parse_str($jsonStr,$data);
        log_record(['data'=>$data]);

        //查询订单
        if($this->checkOrder($data['orderId'])){
//            log_record('开始执行订单状态变更'.$data['orderId']);
            // 实例化订单模型
            $model = $this->getOrderModel($data['orderId'], OrderTypeEnum::ORDER);
            // 订单信息
            // $order = $model->getOrderInfo();
            // 订单支付成功业务处理
            $status = $model->onPaySuccess(OrderPayTypeEnum::SMPAY, $data);
            if ($status == false) {
                $this->returnCode(false, $model->getError());
            }
//            log_record('订单状态变更完毕');
        }
        // 返回状态
        $this->returnCode(true, 'OK');
    }

    /**
     * 检查订单是否交易成功
     * @param $orderId
     * @param $storeId
     * @return bool
     */
    private function checkOrder($orderId){
        //支付通道
        $payClass = new ChannelPay();
        $params = [
            'orderId' => $orderId
        ];
        $order = $payClass->sendSM('order.orderQuery',$params,getStoreId());
        if($order->getCode()){
            $response = $order->getResponse();
            if($response->data->status == '01'){
                return true;
            }
        }
        return false;
    }

    /**
     * 返回状态给微信服务器
     * @param boolean $returnCode
     * @param string $msg
     */
    private function returnCode($returnCode = true, $msg = null)
    {
        // 返回状态
        $return = [
            'return_code' => $returnCode ? 'SUCCESS' : 'FAIL',
            'return_msg' => $msg ?: 'OK',
        ];
        // 记录日志
        log_record([
            'name' => '返回微信支付状态',
            'data' => $return
        ]);
        die($this->toXml($return));
    }

    /**
     * 输出xml字符
     * @param $values
     * @return bool|string
     */
    private function toXml($values)
    {
        if (!is_array($values)
            || count($values) <= 0
        ) {
            return false;
        }

        $xml = "<xml>";
        foreach ($values as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }

    /**
     * 实例化订单模型 (根据attach判断)
     * @param $orderNo
     * @param null $attach
     * @return mixed
     */
    private function getOrderModel($orderNo,$order_type)
    {
        // 判断订单类型返回对应的订单模型
        $model = $this->modelClass[$order_type];
        return new $model($orderNo);
    }
}
